require('dotenv').config();
const Koa = require('koa');
const Router = require("@koa/router");
const bodyParser = require('koa-bodyparser');
const router = new Router();
const authRoutes = require('./routes/auth');
const noteRoutes = require('./routes/notes');
const testRoutes = require('./routes/test'); // 添加测试路由
const db = require('./models/db');

const app = new Koa();
const PORT = 9000;

db.query('SELECT NOW()', (err, res) => {
  if (err) {
    console.error('Error connecting to the database:', err.stack);
  } else {
    console.log('Successfully connected to the database. Server time:', res.rows[0].now);
  }
});

app.use(bodyParser());

// 自动部署
router.post("/webhook", async (ctx) => {
  ctx.body = { success: true, message: "部署已开始!" };
  setTimeout(() => {
    exec("/var/www/note-koa/deploy.sh", (error, stdout, stderr) => {
      if (error) {
        console.error("❌ 部署失败:", error.message);
        console.error(stderr);
      } else {
        console.log("✅ 部署成功:\n", stdout);
      }
    });
  }, 1000);
});

app.use(router.routes()).use(router.allowedMethods());
app.use(authRoutes.routes());
app.use(authRoutes.allowedMethods());
app.use(testRoutes.routes());
app.use(testRoutes.allowedMethods());

noteRoutes.prefix('/notes');
app.use(noteRoutes.routes());
app.use(noteRoutes.allowedMethods());

app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = { error: err.message || 'Internal Server Error' };
    console.error('Unhandled error:', err);
  }
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

module.exports = app; // For testing purposes
